<?php
namespace admin\action;

use api\utils\PayApiClient;
use herosphp\bean\Beans;
use herosphp\http\HttpRequest;
use herosphp\utils\AjaxResult;

/**
 * mpe action
 * @package admin\action
 * @author yangjian<yangjian102621@gmail.com>
 */
class MpeAction extends CommonAction {

    protected $serviceBean = 'app.mpe.service';
    protected $actionTitle = 'MPE';

    //数据列表页面
    public function index( HttpRequest $request ) {
        $mobile = $request->getParameter('mobile', 'trim');
        $name = $request->getParameter('contacter', 'trim');
        $level2_domain = $request->getParameter('level2_domain', 'trim');
        $domain = $request->getParameter('domain', 'trim');
        $status = $request->getParameter('status', 'trim');
        $starttime = $request->getParameter('starttime', 'trim');
        $endtime = $request->getParameter('endtime', 'trim');

        if ( $status === '' ) {
            $status = '-1';
            $request->addParameter('status', '-1');
        }

        $conditions = array('trash' => 0);
        if ( $mobile ) $conditions = array('mobile' => "%{$mobile}%");
        if ( $name ) $conditions = array('contacter' => "%{$name}%");
        if ( $level2_domain ) $conditions['level2_domain'] = "%{$level2_domain}%";
        if ( $domain ) $conditions['domain'] = "%{$domain}%";
        if ( $status != '-1' ) $conditions['status'] = $status;
        if ( $starttime ) $conditions['addtime']['>'] = $starttime.' 00:00:00';
        if ( $endtime ) $conditions['addtime']['<'] = $endtime.' 24:00:00';

        $this->setConditions($conditions);
        $this->assign('tableHeader', array('公司名称','联系人','联系电话','虚拟结算户名称','虚拟结算户帐号','二级域名','一级域名','开通时间','服务期限','应用状态'));

        if( $request->getParameter('__export') == 1 ) {
            $this->export($request); //导出数据

        } else { //加载视图显示数据
            parent::index($request);
            $this->setView('app/mpe_index');
            $this->assign('cstatus', array('0' => '禁用', '1' => '启用'));
            $this->assign("title", $this->actionTitle."列表");
            $this->assign('breadcrumb', array('MPE管理',$this->getTemplateVar('title')));
            $this->assign('breadUrl', array('javascript:;','javascript:;'));
        }

    }

    //数据添加页面
    public function add(HttpRequest $request) {
        $this->loadApps();
        $this->setView('app/mpe_add');
        $this->assign("title", $this->actionTitle."开通");
        $this->assign('breadcrumb', array('MPE管理',$this->actionTitle.'列表',$this->getTemplateVar('title')));
        $this->assign('breadUrl', array('javascript:;',url('admin/mpe/index'),'javascript:;'));
    }

    //数据编辑页面
    public function edit(HttpRequest $request) {
        parent::edit($request);
        $item = $this->getTemplateVar('item');

        if ( empty($item) ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, null, $item);
    }

    //加载app
    public function loadApps() {
        $appService = Beans::get('app.app.service');
        $this->assign('apps', $appService->getItems(array('status' => 1)));
    }

    //插入数据操作
    public function insert(HttpRequest $request) {

        $data = $request->getParameter('data');
        $service = Beans::get($this->serviceBean);
        if( $service->count(array('level2_domain'=>$data['level2_domain'])) > 0 ){
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, '开通失败，该二级域名已被绑定.');
        }
        $data['addtime'] = date('Y-m-d H:i:s');
        if ( $data['end_time'] == '' ) {
            $data['end_time'] = null;
        }
        parent::__insert($data);

    }

    //更新数据操作
    public function update(HttpRequest $request) {

        $data = $request->getParameter('data');
        $level2_domain = $request->getParameter('level2_domain');
        $service = Beans::get($this->serviceBean);

        if( $data['level2_domain'] != $level2_domain
            && $service->count(array('level2_domain'=>$data['level2_domain'])) > 0 ){
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, '更新失败，该二级域名已被绑定.');
        }
        $id = $request->getParameter('id', 'trim');
        if ( $data['end_time'] == '' ) {
            $data['end_time'] = null;
        }
        if ( $data['admin_pass'] == '' ) unset($data['admin_pass']);
        parent::__update($data, $id);

    }

    /**
     * 启用|禁用MPE
     * @param HttpRequest $request
     */
    public function set(HttpRequest $request) {
        $value = $request->getParameter('value', 'trim');
        $id = $request->getParameter('id', 'trim');

        if ( empty($id) ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        $service = Beans::get($this->getServiceBean());
        if ( $value == '1' ) {
            $result = $service->start($id);
        } elseif ( $value == '0' ) {
            $result = $service->stop($id);
        }
        if ( $result ) {
            //记录操作日志
            if ( $value == 1 ) $opt = '启用';
            else $opt = '关闭';

            $request->addParameter('logmessage', $opt.$this->actionTitle." [{$this->getOptobjById($id)}] ");
            AjaxResult::ajaxSuccessResult();
        } else {
            AjaxResult::ajaxFailtureResult();
        }
    }

    //绑定大塑支付账户
    public function bindUser(HttpRequest $request) {
        $username = $request->getParameter('username', 'trim');
        $appid = $request->getParameter('appid', 'trim');
        //调用支付会员系统API
        $resVo = PayApiClient::send('api/user/bindApp', array('username' => $username));
        if ( !$resVo->isSucess() ) AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, $resVo->getMessage());

        $user = $resVo->getItem();
        //已经被绑定过的用户不能再绑定
        $mpeService = Beans::get($this->getServiceBean());
        if ( $mpeService->count(array('userid' => $user['userid'], 'appid' => $appid)) > 0 ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, '绑定失败，改用户已经被绑定了一个MPE了.');
        }

        AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, $user);
    }

    //删除应用到回收站
    public function delete(HttpRequest $request) {
        $id = $request->getParameter('id', 'trim');
        if ( empty($id) ) {
            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, self::NO_RECORDS);
        }
        $service = Beans::get($this->serviceBean);
        if ( $service->set('trash', 1, $id) ) {
            AjaxResult::ajaxSuccessResult();
        } else {
            AjaxResult::ajaxFailtureResult();
        }
    }

    //导出数据
    protected function export(HttpRequest $request) {
        if( $request->getParameter('__export') == 1 ){
            $ids = $request->getParameter('ids');
            if( $ids ){
                $conditions['id']['$in']=$ids;
                $this -> setConditions($conditions);
            }
            $this->setPagesize(getConfig('export_max_count'));
            $service = Beans::get($this->getServiceBean());
            $items = $service->where($this->getConditions())->limit(1, $this->getPagesize())->sort(array('addtime' => -1))->find();
            $excel = array();
            foreach($items as $k => $v)
            {
                $tmp = array();
                $tmp[] = $v["company"];
                $tmp[] = $v["contacter"];
                $tmp[] = $v["mobile"];
                $tmp[] = $v["virtual_name"];
                $tmp[] = $v["virtual_account"];
                $tmp[] = $v["level2_domain"];
                $tmp[] = $v["domain"];
                $tmp[] = $v["addtime"];
                $tmp[] = $v["end_time"] ? $v['start_time'].'-'.$v['end_time'] : '永久开通';
                $tmp[] = $v['status'] == 1 ? '启用' : '禁用';
                $excel[] = $tmp;
            }
            $header = $this->getTemplateVar('tableHeader');
            phpexcel("MPE列表",$header,$excel);
            exit();
        }
    }
}
